<template>
  <div class="edit-page">
    <NavBar />
    
    <div class="main-content" v-if="!postsStore.loading">
      <div class="container">
        <div class="edit-header">
          <h1 class="page-title">编辑文章</h1>
          <div class="header-actions">
            <el-button @click="saveDraft" :loading="saving">
              <el-icon><Document /></el-icon>
              保存草稿
            </el-button>
            <el-button type="primary" @click="updatePost" :loading="updating">
              <el-icon><Upload /></el-icon>
              更新文章
            </el-button>
          </div>
        </div>
        
        <div class="edit-form">
          <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="80px"
            class="post-form"
          >
            <el-form-item label="标题" prop="title">
              <el-input
                v-model="form.title"
                placeholder="请输入文章标题"
                size="large"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>
            
            
            <el-form-item label="内容" prop="content" class="content-editor">
              <MarkdownEditor v-model="form.content" />
            </el-form-item>
            
            <el-form-item label="分类" prop="category_id">
              <el-select
                v-model="form.category_id"
                placeholder="选择分类"
                clearable
                style="width: 200px"
              >
                <el-option
                  v-for="category in categories"
                  :key="category.id"
                  :label="category.name"
                  :value="category.id"
                />
              </el-select>
            </el-form-item>
            
            <el-form-item label="标签" prop="tag_ids">
              <TagSelector
                v-model="form.tag_ids"
                :available-tags="availableTags"
                @tag-created="onTagCreated"
              />
            </el-form-item>
            
            <el-form-item>
              <div class="form-options">
                <el-checkbox v-model="form.is_featured">设为精选</el-checkbox>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>
      
      <!-- 悬浮操作按钮 -->
      <div class="floating-actions">
        <el-button 
          @click="saveDraft" 
          :loading="saving"
          class="floating-btn draft-btn"
        >
          <el-icon><Document /></el-icon>
          保存草稿
        </el-button>
        <el-button 
          type="primary" 
          @click="updatePost" 
          :loading="updating"
          class="floating-btn publish-btn"
        >
          <el-icon><Upload /></el-icon>
          更新文章
        </el-button>
      </div>
    </div>
    
    <!-- 加载状态 -->
    <div v-else class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { usePostsStore } from '@/stores/posts'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import api from '@/utils/api'
import NavBar from '@/components/NavBar.vue'
import MarkdownEditor from '@/components/MarkdownEditor.vue'
import TagSelector from '@/components/TagSelector.vue'
import type { PostUpdate } from '@/types'

const route = useRoute()
const router = useRouter()
const postsStore = usePostsStore()

const formRef = ref<FormInstance>()
const saving = ref(false)
const updating = ref(false)

const form = reactive({
  title: '',
  content: '',
  excerpt: '',
  cover_image: '',
  is_published: false,
  is_featured: false,
  category_id: undefined as number | undefined,
  tag_ids: [] as number[]
})

// 标签验证逻辑已经移到TagSelector组件中

// 处理新标签创建
const onTagCreated = (newTag: any) => {
  // 将新标签添加到可用标签列表中
  availableTags.value.push(newTag)
}

const rules: FormRules = {
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { min: 5, max: 200, message: '标题长度在5到200个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入文章内容', trigger: 'blur' },
    { min: 10, message: '文章内容不能少于10个字符', trigger: 'blur' }
  ]
}

// 分类和标签数据
const categories = ref<any[]>([])
const tags = ref<any[]>([])
const suggestedTags = ref<any[]>([])
const availableTags = ref<any[]>([])

const loadPost = async () => {
  try {
    const postId = route.params.id as string
    if (!postId) {
      throw new Error('缺少文章ID')
    }
    await postsStore.fetchPost(postId)
    
    if (postsStore.currentPost) {
      form.title = postsStore.currentPost.title || ''
      form.content = postsStore.currentPost.content || ''
      form.excerpt = postsStore.currentPost.excerpt || ''
      form.cover_image = postsStore.currentPost.cover_image || ''
      form.is_published = postsStore.currentPost.is_published || false
      form.is_featured = postsStore.currentPost.is_featured || false
      form.category_id = postsStore.currentPost.category?.id || undefined
      form.tag_ids = postsStore.currentPost.tags?.map(tag => tag.id) || []
      
      console.log('加载文章数据:', {
        title: form.title,
        cover_image: form.cover_image,
        original_cover_image: postsStore.currentPost.cover_image,
        has_cover_image: !!form.cover_image
      })
    }
  } catch (error) {
    console.error('加载文章失败:', error)
    ElMessage.error('文章不存在或已被删除')
    router.push('/posts')
  }
}

const saveDraft = async () => {
  if (!formRef.value) return
  
  try {
    // 草稿保存时，只验证必填字段，不进行完整验证
    if (!form.title?.trim()) {
      ElMessage.error('请输入文章标题')
      return
    }
    
    if (!form.content?.trim()) {
      ElMessage.error('请输入文章内容')
      return
    }
    
    saving.value = true
    
    const postId = route.params.id as string
    const draftData = {
      title: form.title?.trim() || '',
      content: form.content?.trim() || '',
      excerpt: form.excerpt || '',
      cover_image: form.cover_image || '',
      is_published: false, // 保存草稿时，强制设置为false
      is_featured: form.is_featured || false,
      category_id: form.category_id || undefined,
      tag_ids: form.tag_ids || []
    }
    
    console.log('保存草稿数据:', draftData)
    
    await postsStore.updatePost(postId, draftData)
    
    ElMessage.success('草稿保存成功')
  } catch (error) {
    console.error('保存草稿失败:', error)
    ElMessage.error('保存草稿失败，请重试')
  } finally {
    saving.value = false
  }
}

const loadCategories = async () => {
  try {
    const response = await api.get('/posts/categories')
    console.log('分类API响应:', response.data)
    
    if (Array.isArray(response.data)) {
      categories.value = response.data
    } else {
      console.warn('分类数据格式不正确:', response.data)
      categories.value = []
    }
  } catch (error) {
    console.error('加载分类失败:', error)
    // 如果API失败，使用默认分类
    categories.value = [
      { id: 1, name: '技术' },
      { id: 2, name: '生活' },
      { id: 3, name: '随笔' }
    ]
  }
}

const loadTags = async () => {
  try {
    const response = await api.get('/posts/tags')
    console.log('标签API响应:', response.data)
    
    if (Array.isArray(response.data)) {
      // 确保每个标签对象都有正确的结构
      const validTags = response.data.filter(tag => tag && typeof tag.id === 'number' && typeof tag.name === 'string')
      tags.value = validTags
      suggestedTags.value = validTags.slice(0, 5)
      availableTags.value = validTags
    } else {
      console.warn('标签数据格式不正确:', response.data)
      tags.value = []
      suggestedTags.value = []
      availableTags.value = []
    }
  } catch (error) {
    console.error('加载标签失败:', error)
    // 如果API失败，使用默认标签
    const defaultTags = [
      { id: 1, name: 'Vue', color: '#4fc08d' },
      { id: 2, name: 'JavaScript', color: '#f7df1e' },
      { id: 3, name: 'Python', color: '#3776ab' },
      { id: 4, name: 'FastAPI', color: '#009688' }
    ]
    tags.value = defaultTags
    suggestedTags.value = defaultTags.slice(0, 5)
    availableTags.value = defaultTags
    console.log('Edit使用默认标签:', { defaultTags, suggestedTags: suggestedTags.value, availableTags: availableTags.value })
  }
}

// 标签处理函数
const handleTagChange = (value: any[]) => {
  console.log('标签选择变化:', value)
  // 确保所有值都是有效的数字类型
  form.tag_ids = (value || []).map(v => {
    if (v === null || v === undefined || v === '') {
      return null
    }
    const num = typeof v === 'string' ? parseInt(v) : Number(v)
    return isNaN(num) ? null : num
  }).filter((v): v is number => v !== null) // 过滤掉无效值
  
  // 确保数据有效性
  console.log('处理后的标签ID:', form.tag_ids || [])
}

const handleCreateTag = async (query: string) => {
  try {
    // 创建新标签
    const response = await api.post('/posts/tags', {
      name: query,
      description: '',
      color: '#409EFF'
    })
    
    // 确保新标签有正确的结构
    const newTag = response.data
    if (newTag && typeof newTag.id === 'number' && typeof newTag.name === 'string') {
      // 添加到标签列表
      tags.value.push(newTag)
      availableTags.value.push(newTag)
      
      // 自动选中新创建的标签
      if (!(form.tag_ids || []).includes(newTag.id)) {
        (form.tag_ids || []).push(newTag.id)
      }
      
      ElMessage.success(`标签 "${query}" 创建成功`)
      return newTag.id
    } else {
      throw new Error('创建的标签格式不正确')
    }
  } catch (error) {
    console.error('创建标签失败:', error)
    ElMessage.error('创建标签失败')
    throw error
  }
}

// 获取标签名称
const getTagName = (tagId: number | string | null) => {
  if (tagId === null || tagId === undefined) {
    return '未知标签'
  }
  
  let id: number
  if (typeof tagId === 'string') {
    id = parseInt(tagId)
    if (isNaN(id)) {
      console.warn('无效的标签ID:', tagId)
      return `标签${tagId}`
    }
  } else {
    id = Number(tagId)
    if (isNaN(id)) {
      console.warn('无效的标签ID:', tagId)
      return `标签${tagId}`
    }
  }
  
  const tag = availableTags.value.find(t => t && t.id === id)
  if (!tag) {
    console.warn('标签未找到:', { tagId, id, availableTags: availableTags.value })
    return `标签${id}`
  }
  return tag.name || `标签${id}`
}

// 获取标签颜色
const getTagColor = (tagId: number | string) => {
  let id: number
  if (typeof tagId === 'string') {
    id = parseInt(tagId)
    if (isNaN(id)) {
      return '#409EFF'
    }
  } else {
    id = tagId
  }
  
  const tag = availableTags.value.find(t => t.id === id)
  return tag ? tag.color : '#409EFF'
}

// 添加标签到选择列表
const addTag = (tagId: number) => {
  if (!(form.tag_ids || []).includes(tagId)) {
    (form.tag_ids || []).push(tagId)
  }
}

// 删除标签（从已选择列表中移除）
const removeTag = (tagId: number) => {
  const index = (form.tag_ids || []).indexOf(tagId)
  if (index > -1) {
    (form.tag_ids || []).splice(index, 1)
  }
}

const updatePost = async () => {
  if (!formRef.value) return
  
  try {
    // 更新文章时，进行基本验证
    if (!form.title?.trim()) {
      ElMessage.error('请输入文章标题')
      return
    }
    
    if (!form.content?.trim()) {
      ElMessage.error('请输入文章内容')
      return
    }
    
    if ((form.title?.trim() || '').length < 5) {
      ElMessage.error('标题长度不能少于5个字符')
      return
    }
    
    if ((form.content?.trim() || '').length < 10) {
      ElMessage.error('文章内容不能少于10个字符')
      return
    }
    
    updating.value = true
    
    const postId = route.params.id as string
    const updateData = {
      title: form.title?.trim() || '',
      content: form.content?.trim() || '',
      excerpt: form.excerpt || '',
      cover_image: form.cover_image || '',
      is_published: true, // 更新文章时，强制设置为true（发布文章）
      is_featured: form.is_featured || false,
      category_id: form.category_id || undefined,
      tag_ids: form.tag_ids || []
    }
    
    console.log('编辑文章 - 更新数据:', updateData)
    console.log('编辑文章 - 封面图片:', form.cover_image)
    
    await postsStore.updatePost(postId, updateData)
    
    // 刷新文章列表以更新草稿箱
    await postsStore.fetchPosts({ published_only: false })
    
    ElMessage.success('文章更新成功')
    router.push(`/posts/${postsStore.currentPost?.id}`)
  } catch (error) {
    console.error('更新文章失败:', error)
    ElMessage.error('更新文章失败，请重试')
  } finally {
    updating.value = false
  }
}

// 生成封面图片
const generateCoverImage = async () => {
  try {
    console.log('开始生成封面图片...')
    const response = await api.post('/posts/generate-cover-image')
    form.cover_image = response.data.url
    console.log('生成封面图片成功:', response.data.url)
  } catch (error) {
    console.error('生成封面图片失败:', error)
    // 如果生成失败，使用默认图片
    form.cover_image = 'https://picsum.photos/800/400'
    console.log('使用默认封面图片:', form.cover_image)
  }
}

onMounted(async () => {
  await loadPost()
  
  // 加载分类和标签数据
  await loadCategories()
  await loadTags()
  
  // 如果没有封面图片，生成一个
  if (!form.cover_image || form.cover_image.trim() === '') {
    console.log('文章没有封面图片，正在生成...')
    await generateCoverImage()
  } else {
    console.log('文章已有封面图片，保持原有图片:', form.cover_image)
  }
  
  console.log('最终封面图片状态:', {
    cover_image: form.cover_image,
    has_cover_image: !!form.cover_image
  })
})
</script>

<style scoped>
.edit-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.main-content {
  flex: 1;
  padding: 2rem 0;
  background: #f5f7fa;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 60px;
}

.edit-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
  background: white;
  padding: 1.5rem;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.page-title {
  font-size: 1.5rem;
  font-weight: 700;
  color: #333;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 1rem;
}

.edit-form {
  background: white;
  border-radius: 8px;
  padding: 2rem;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.post-form {
  max-width: none;
}

.form-options {
  display: flex;
  gap: 2rem;
}

.loading-container {
  padding: 2rem;
}

/* 悬浮操作按钮 */
.floating-actions {
  position: fixed;
  bottom: 20px;
  right: 20px;
  display: flex;
  gap: 12px;
  z-index: 1000;
}

.floating-btn {
  height: 48px;
  padding: 0 20px;
  border-radius: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  font-weight: 500;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
}

.floating-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.2);
}

.draft-btn {
  background: white;
  border: 1px solid #dcdfe6;
  color: #606266;
}

.draft-btn:hover {
  background: #f5f7fa;
  border-color: #409eff;
  color: #409eff;
}

.publish-btn {
  background: linear-gradient(135deg, #409eff 0%, #67c23a 100%);
  border: none;
  color: white;
}

.publish-btn:hover {
  background: linear-gradient(135deg, #337ecc 0%, #529b2e 100%);
}

/* 内容编辑器样式 */
.content-editor {
  margin-bottom: 2rem;
  width: 100%;
}

.content-editor :deep(.el-form-item__content) {
  width: 100%;
}

.content-editor :deep(.markdown-editor) {
  width: 100%;
}

/* 标签选择器样式 */
.tag-selector {
  width: 100%;
}

.selected-tags {
  margin-top: 12px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.selected-tags-label {
  font-size: 12px;
  color: #666;
  margin-bottom: 8px;
  font-weight: 500;
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.selected-tag {
  margin: 0;
  transition: all 0.2s ease;
  background: transparent !important;
  border: 2px solid #409eff !important;
  color: #333 !important;
  font-weight: 500;
}

.selected-tag:hover {
  transform: scale(1.05);
  border-color: #337ecc !important;
  background: #f0f9ff !important;
}

.tag-suggestions {
  margin-top: 12px;
  padding: 12px;
  background: #f0f9ff;
  border-radius: 6px;
  border: 1px solid #e0f2fe;
}

.suggestion-label {
  font-size: 12px;
  color: #0369a1;
  margin-bottom: 8px;
  font-weight: 500;
}

.suggestion-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.suggestion-tag {
  cursor: pointer;
  transition: all 0.2s ease;
  margin: 0;
  background: transparent !important;
  border: 1px solid #d0d7de !important;
  color: #333 !important;
  font-weight: 500;
}

.suggestion-tag:hover {
  transform: scale(1.05);
  border-color: #409eff !important;
  background: #f0f9ff !important;
  color: #409eff !important;
}

@media (max-width: 768px) {
  .edit-header {
    flex-direction: column;
    gap: 1rem;
    align-items: stretch;
  }
  
  .header-actions {
    justify-content: center;
  }
  
  .edit-form {
    padding: 1rem;
  }
  
  .form-options {
    flex-direction: column;
    gap: 1rem;
  }
  
  .floating-actions {
    bottom: 10px;
    right: 10px;
    flex-direction: column;
    gap: 8px;
  }
  
  .floating-btn {
    height: 44px;
    padding: 0 16px;
    font-size: 14px;
  }
}
</style>
